package com.fw4j.web.mapping;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fw4j.web.annotation.Controller;
import com.fw4j.web.annotation.RequestMapping;
import com.fw4j.web.annotation.ToJSON;
/**
 * @author 穆仁超
 * URL映射
 * 日期 2013-12-24 16:59
 * 我的QQ群：32894018
 */
public class URLMapping implements Runnable{
	private String filePath = null;
	
	
	
	public URLMapping(String filePath){
		this.filePath = filePath;
	}
	
	public URLMapping(){}
	
	public void setFilePath(String filePath){
		this.filePath = filePath;
	}
	
	public void run() {
		createMapping(scanningClass(this.filePath));
	}
	
	private static Logger logger = LoggerFactory.getLogger(URLMapping.class);
	private static Map<String,String> mapping = new HashMap<String,String>();
	
	public static void setURLMapping(String urlPath,String classPath){
		mapping.put(urlPath, classPath);
	}
	
	public static String getURLMapping(String urlPath){
		return mapping.get(urlPath);
	}
	
    /***
     * 获取指定目录下的所有class文件
     */
	public static List<String> scanningClass(String filePath){
		 List<String> myClassName = new ArrayList<String>(); 
	        File file = new File(filePath); 
	        File[] childFiles = file.listFiles(); 
	        for (File childFile : childFiles) { 
	            if (childFile.isDirectory()) { 
	                    myClassName.addAll(scanningClass(childFile.getPath())); 
	            } else { 
	                String childFilePath = childFile.getPath(); 
	                if (childFilePath.endsWith(".class")) { 
	                    childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf(".")); 
	                    childFilePath = childFilePath.replace("\\", "."); 
	                    myClassName.add(childFilePath); 
	                }//end if
	            }//end if
	        } //end for
	        return myClassName; 
	}
	
    /***
     * 通过返射获取文件中的注释，记录url请求地址和请求类型与类方法的对应关联
     */ 
	public static void createMapping(List<String> files){
		for(String file : files){
			Object c;
			try {
				c = Class.forName(file).newInstance();
				StringBuffer urlPath = new StringBuffer();
				Controller cl = c.getClass().getAnnotation(Controller.class);			
				if(cl!=null){
					RequestMapping rm = c.getClass().getAnnotation(RequestMapping.class);	
					if(rm != null){
						if(!rm.value().equals("/"))
							urlPath.append(rm.value().trim());
					}//end if
					Method[] ms = c.getClass().getMethods();
					for(Method m : ms){
						Annotation[] ans = m.getAnnotations();
						for(Annotation a : ans){
							if(a instanceof RequestMapping){
								rm = (RequestMapping)a;
								if(rm != null){
									//urlPath.append(rm.value().trim());
									setURLMapping(urlPath.toString()+rm.value().trim()+"$"+rm.method(),file+"_"+m.getName());
									logger.info("["+urlPath.toString()+rm.value().trim()+"$"+rm.method()+" >> "+file+"_"+m.getName()+"]");
									//urlPath.replace(urlPath.indexOf(rm.value().trim()), urlPath.length(),"");
								}//end if
							}//end if
						}//end for
					}//end for
				}//end if
			}catch(InstantiationException ex){
				
			} catch (Exception ex){
				ex.printStackTrace();
			}
		}
	}
	
}